package com.tiantian.service;



import java.util.HashMap;
import java.util.Map;

import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import com.html5.R;
import com.music.model.Music;
import com.music.utils.DownloadFile;
import com.music.utils.Helper;

public class DownloadService extends Service {

	private NotificationManager notificationManager=null;
	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		
		Music music=(Music)intent.getSerializableExtra("music");
		
		Thread thread=new Thread(new DownloadThread(music));
		thread.start();
	   
		return super.onStartCommand(intent, flags, startId);
	}
	class DownloadThread implements Runnable{
    	private Music music=null;
    	public DownloadThread(Music music){
    		this.music=music;
    	}
		@Override
		public void run() {
			System.out.println("启动");
			 notificationManager=(NotificationManager)DownloadService.this.getSystemService(NOTIFICATION_SERVICE);
			 Helper helper=new Helper();
			 helper.showNotification(notificationManager,R.drawable.icon,"正在下载"+music.getName(),DownloadService.this,DownloadService.class);
			DownloadFile df=new DownloadFile();
			int state=df.downloadMedia(music.getMusicUrl(),"TianTianMusic",music.getName()+".mp3");
			String message=null;
			Map<String, String> param=new HashMap<String, String>();
			param.put("id", this.music.getId());
			param.put("m", this.music.getName());
			if(state==-1)
			{
				message="下载失败";
			}else if(state==0)
			{
				if(this.music.getLrc()!=null&&!this.music.getLrc().equals(""))
				{
					System.out.println("下载歌词");
					df.getMethod(music.getLrc(),param,"TianTianMusic",music.getName()+".lrc");
				}
				message="文件已经存在，不要重复下载";
			}else if(state==1)
			{
				if(this.music.getLrc()!=null&&!this.music.getLrc().equals(""))
				{
					System.out.println("下载歌词");
					df.getMethod(music.getLrc(),param,"TianTianMusic",music.getName()+".lrc");
				}
				message="下载成功";
			}
			 helper.showNotification(notificationManager,R.drawable.icon, message,DownloadService.this,DownloadService.class);
		}
    }
}
